package ml.kupin.search.dao.impl;

import ml.kupin.search.dao.SearchDao;
import ml.kupin.common.vo.IndexItem;
import ml.kupin.common.vo.SearchResult;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 小柯(Allen Kerr) on 17.5.3 10:22.
 */
@Repository
public class SearchDaoImpl implements SearchDao {

    @Autowired
    private SolrServer solrServer;

    @Override
    public SearchResult<IndexItem> search(SolrQuery solrQuery) throws Exception {
        //执行搜索，获得queryResponse对象
        QueryResponse queryResponse = solrServer.query(solrQuery);
        //取结果集
        SolrDocumentList results = queryResponse.getResults();
        //总记录数
        Long recourdCount = results.getNumFound();
        //取高亮
        Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
        //封装结果
        List<IndexItem> itemList = new ArrayList<>();
        for (SolrDocument doc : results) {
            IndexItem indexItem = new IndexItem();
            indexItem.setId((String) doc.get("id"));
            //=============标题高亮=============
            List<String> list = highlighting.get(doc.get("id")).get("item_title");
            String title = null;
            if (list != null && list.size() > 0) {
                title = list.get(0);
            } else {
                title = (String) doc.get("item_title");
            }
            indexItem.setTitle(title);
            //=============标题高亮=============
            indexItem.setSell_point((String) doc.get("item_sell_point"));
            if (doc.get("item_price") != null) {//null无法转long，所以需要判断
                indexItem.setPrice((Long) doc.get("item_price"));
            }
            indexItem.setImage((String) doc.get("item_image"));
            indexItem.setCategory_name((String) doc.get("item_category_name"));
            itemList.add(indexItem);
        }
        SearchResult<IndexItem> searchResult = new SearchResult<>();
        searchResult.setItemList(itemList);
        searchResult.setRecourdCount(recourdCount);
        return searchResult;
    }
}
